<template>
  <Modal :width="1000" v-model:visible="open" @ok="handleSuccess">
    <div class="mt-20px max-h-500px overflow-auto w-full p-2">
      <Tabs
        v-model:activeKey="newData.activeKey"
        centered
        destroyInactiveTabPane
        @change="handleActiveKey"
      >
        <TabPane key="1" tab="嵌套表">
          <NestTableForm
            style="margin-bottom: 8px"
            type="1"
            v-model:modelValue="newData.nestTableForm"
            ref="nestTableFormRef"
            @module-change-left="handleModuleChangeLeft"
            v-if="newData.activeKey == '1'"
          />
          <LimitsAuthority style="margin-bottom: 8px" v-model:modelValue="newData.authority" />
          <FormView
            :formCode="newData?.nestTableForm?.formCode"
            v-model:modelValue="newData.formViewId"
            v-if="mode === 'nest_table'"
          />
          <ViewTable style="margin-bottom: 8px" :formCode="newData?.nestTableForm?.formCode" />
          <TotalField
            v-model:modelValue="newData.amountFields"
            :formCode="newData?.nestTableForm?.formCode"
          />
        </TabPane>
        <TabPane key="2" tab="拉单">
          <NestTableForm
            style="margin-bottom: 8px"
            type="2"
            ref="nestTableFormRef"
            v-model:modelValue="newData.nestTableForm"
            :formGetFieldsData="formGetFieldsData"
            @module-change-left="handleModuleChangeLeft"
            @module-change-right="handleModuleChangeRight"
            v-if="newData.activeKey == '2'"
          />
          <FieldMapping
            style="margin-bottom: 8px"
            v-model:modelValue="newData.fieldMapping"
            :formGetFieldsData="formGetFieldsData"
            :formGetFieldsDataTo="formGetFieldsDataTo"
            ref="fieldMappingRef"
          />
          <LimitsAuthority style="margin-bottom: 8px" v-model:modelValue="newData.authority" />
          <FormView
            :formCode="newData?.nestTableForm?.destFormFormCode"
            v-model:modelValue="newData.formViewId"
            v-if="mode === 'nest_table'"
          />
          <ViewTable style="margin-bottom: 8px" :formCode="newData?.nestTableForm?.destForm" />
          <TotalField
            v-model:modelValue="newData.amountFields"
            :formCode="newData?.nestTableForm?.destFormFormCode"
          />
        </TabPane>
        <TabPane key="3" tab="查询拉单" v-if="false">
          <NestTableForm
            style="margin-bottom: 8px"
            type="3"
            ref="nestTableFormRef"
            v-model:modelValue="newData.nestTableForm"
            @module-change-left="handleModuleChangeLeft"
            @module-change-right="handleModuleChangeRight"
            @set-query-id="handleSetQueryId"
            v-if="newData.activeKey == '3'"
          />
          <ConditionalMapping
            style="margin-bottom: 8px"
            v-model:modelValue="newData.conditionalMapping"
            :formGetFieldsDataTo="formGetFieldsDataTo"
            :formGetFieldsData="condFieldList"
            ref="conditionalMappingRef"
          />
          <FieldMapping
            style="margin-bottom: 8px"
            v-model:modelValue="newData.fieldMapping"
            :formGetFieldsData="sourceFieldsList"
            :formGetFieldsDataTo="formGetFieldsDataTo"
            ref="fieldMappingRef"
          />
          <LimitsAuthority style="margin-bottom: 8px" v-model:modelValue="newData.authority" />
          <TotalField
            v-model:modelValue="newData.amountFields"
            :formCode="newData?.nestTableForm?.destFormFormCode"
          />
        </TabPane>
      </Tabs>
    </div>
  </Modal>
</template>
<script setup lang="ts">
  import { ref, PropType, computed, watch, nextTick } from 'vue';
  import { Modal, Tabs } from 'ant-design-vue';
  import LimitsAuthority from './modules/LimitsAuthority.vue';
  import TotalField from './modules/TotalField.vue';
  import FieldMapping from './modules/FieldMapping.vue';
  import NestTableForm from './modules/NestTableForm.vue';
  import ViewTable from './modules/ViewTable.vue';
  import ConditionalMapping from './modules/ConditionalMapping.vue';
  import FormView from './modules/FormView.vue';

  import {
    getFormGetFields,
    getVisualGetCondField,
    getVisualGetSourceFields,
    getFieldsByModuleCode,
  } from '/@/api/flowManage/flowManage';
  import { isArray } from '/@/utils/is';
  import { deepClone } from '/@/views/formDesigner/utils';
  const TabPane = Tabs.TabPane;
  const emit = defineEmits(['success', 'update:visible']);
  const props = defineProps({
    visible: {
      type: Boolean as PropType<Boolean>,
      default: false,
    },
    data: {
      type: Object as PropType<Object>,
      default: () => {},
    },
    mode: {
      type: String,
      default: 'nest_table',
    },
  });

  const nestTableFormRef = ref<any>(null);

  const open = computed({
    get() {
      return props.visible;
    },
    set(e) {
      emit('update:visible', e);
    },
  });
  const newData = ref<Recordable>({
    nestTableForm: {},
    authority: {},
    amountFields: [],
    fieldMapping: [],
    conditionalMapping: [],
    activeKey: '1',
    formViewId: -1,
  });
  watch(
    () => props.data,
    async (newVal) => {
      if (newVal && Object.keys(newVal).length) {
        newData.value = deepClone(newVal);

        console.log('newData.value', newData.value);
        if (newData.value.nestTableForm?.destForm && newData.value.nestTableForm?.forms) {
          newData.value.activeKey = '2';
        } else {
          if (!newData.value.activeKey) {
            newData.value.activeKey = '1';
          }
        }

        await nextTick();
        getFormGetFieldsData();
        getFormGetFieldsDataTo();
        getQueryId();
        getVisualGetSourceFieldsData();
      }
    },
    {
      immediate: true,
    },
  );
  const handleClose = () => {
    open.value = false;
  };

  const fieldMappingRef = ref<any>(null);
  const conditionalMappingRef = ref<any>(null);

  const handleModuleChangeLeft = (val, node) => {
    console.log('val', val, 'node', node);
    newData.value.nestTableForm.forms = val; // 模块编码
    newData.value.nestTableForm.formCode = node?.formCode; // 对应的表单编码
    getFormGetFieldsData();
    fieldMappingRef.value?.handleInit();
    conditionalMappingRef.value?.handleInit();
  };
  const handleModuleChangeRight = (val, node) => {
    newData.value.nestTableForm.destForm = val; // 模块编码
    newData.value.nestTableForm.destFormFormCode = node?.formCode; // 对应的表单编码
    getFormGetFieldsDataTo();
    fieldMappingRef.value?.handleInit();
    conditionalMappingRef.value?.handleInit();
  };
  const formGetFieldsData = ref<Recordable[]>([]);
  //获取源字段
  const getFormGetFieldsData = () => {
    console.log('newData.value.nestTableForm', newData.value.nestTableForm);
    try {
      // const { query } = currentRoute.value;
      let fCode;
      if (newData.value.nestTableForm?.destForm && newData.value.nestTableForm?.forms) {
        // 拉单
        fCode = newData.value.nestTableForm.forms;
      } else if (newData.value?.nestTableForm?.formCode) {
        fCode = newData.value.nestTableForm.formCode;
      }

      getFieldsByModuleCode({ moduleCode: fCode }).then((res) => {
        formGetFieldsData.value = res || [];
        if (isArray(formGetFieldsData.value)) {
          formGetFieldsData.value.forEach((item) => {
            item.label = item.title;
            item.value = item.name;
            delete item.options;
          });
        }
      });
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };

  const formGetFieldsDataTo = ref<Recordable[]>([]);
  //获取目标字段
  const getFormGetFieldsDataTo = () => {
    try {
      if (newData.value?.nestTableForm?.destFormFormCode) {
        getFormGetFields({ formCode: newData.value.nestTableForm.destFormFormCode }).then((res) => {
          formGetFieldsDataTo.value = res || [];
          if (isArray(formGetFieldsDataTo.value)) {
            formGetFieldsDataTo.value.forEach((item) => {
              item.label = item.title;
              item.value = item.name;
              delete item.options;
            });
          }
        });
      }
    } catch (err) {
      console.log('getFormGetFields', err);
    }
  };

  //选择查询回调
  const handleSetQueryId = (val) => {
    newData.value.nestTableForm.queryId = val;
    getQueryId();
    getVisualGetSourceFieldsData();
    fieldMappingRef.value?.handleInit();
    conditionalMappingRef.value?.handleInit();
  };
  const condFieldList = ref<Recordable[]>([]);
  //获取关联查询id
  const getQueryId = () => {
    condFieldList.value = [];
    try {
      if (newData.value?.nestTableForm?.queryId)
        getVisualGetCondField({ id: newData.value.nestTableForm.queryId }).then((res) => {
          condFieldList.value = res || [];
        });
    } catch (err) {
      console.log('getVisualGetCondField', err);
    }
  };
  const sourceFieldsList = ref<Recordable[]>([]);
  //获取关联查询id 源字段
  const getVisualGetSourceFieldsData = () => {
    sourceFieldsList.value = [];
    try {
      if (newData.value?.nestTableForm?.queryId)
        getVisualGetSourceFields({ id: newData.value.nestTableForm.queryId }).then((res) => {
          sourceFieldsList.value = res || [];
          sourceFieldsList.value.forEach((item) => {
            item.value = item.name;
          });
          console.log('sourceFieldsList', sourceFieldsList.value);
        });
    } catch (err) {
      console.log('getVisualGetSourceFieldsData', err);
    }
  };

  const handleActiveKey = () => {
    newData.value.nestTableForm = {};
    newData.value.formViewId = '';
  };

  const handleSuccess = () => {
    const { submit } = nestTableFormRef.value;
    submit().then((res) => {
      console.log('res', res);
      console.log('newData.value', newData.value);
      emit('success', newData.value);
      handleClose();
    });
  };
</script>
